import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:rocketim/src/pages/meeting_room/dialog.dart';
import 'package:rocketim/src/pages/select_contacts/select_contacts_logic.dart';
import 'package:rocketim/src/res/strings.dart';
import 'package:rocketim/src/routes/app_navigator.dart';
import 'package:rocketim/src/routes/app_pages.dart';
import 'package:rocketim/src/utils/logger_util.dart';
import 'package:rocketim/src/widgets/app_view.dart';
import 'package:ym_flutter_push/ym_flutter_push.dart';

import 'core/controller/db_controller.dart';
import 'core/controller/jpush_controller.dart';
// import 'core/controller/permission_controller.dart';
// import 'core/controller/permission_controller.dart';
// import 'core/controller/push_controller.dart';

class EnterpriseChatApp extends StatefulWidget {
  const EnterpriseChatApp({Key? key}) : super(key: key);

  @override
  _EnterpriseChatAppState createState() => _EnterpriseChatAppState();
}

class _EnterpriseChatAppState extends State<EnterpriseChatApp> {
  _EnterpriseChatAppState();
  String _registerId = 'Unknown';
  String _data = "";
  final List<PushMessage> messages = [];

  @override
  void initState() {
    super.initState();
    _initChannel();
  }

  Future<void> _initChannel() async {
    // 获取注册ID
    var registerId = await YmFlutterPush.instance.getRegisterInfo();
    print('-------------registerId: $registerId');
    setState(() {
      _registerId = registerId.toString();
    });

    // 监听推送消息
    YmFlutterPush.instance.onMessageReceived().listen(
      (PushMessage message) {
        print('收到推送消息: ${message.toString()}');
        setState(() {
          messages.add(message);
        });

        // 根据消息类型处理
        switch (message.type) {
          case 'notification':
            print('收到通知: ${message.title}');
            handleNotification(message);
            break;

          case 'passthrough':
            print('收到透传消息: ${message.payload}');
            handlePassthrough(message);
            break;

          case 'click':
            print('用户点击了通知: ${message.title}');
            handleNotificationClick(message);
            break;
        }
      },
      onError: (error) {
        print('推送消息错误: $error');
      },
    );

    var channel = MethodChannel("cn.nulltech.app.rocketim");
    channel.setMethodCallHandler((call) async {
      // 同样也是根据方法名分发不同的函数
      switch (call.method) {
        case "shareFile":
          {
            String filePath = call.arguments;
            print("filepath from dart method call: " + filePath);
            await AppNavigator.startSelectContacts(
              action: SelAction.SHARE,
              shareFilePath: filePath,
              defaultCheckedUidList: [],
            );
          }
          break;
      }
      return 0;
    });
  }

  void handleNotification(PushMessage message) {
    // 处理通知消息
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(message.title),
        content: Text(message.description),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  void handlePassthrough(PushMessage message) {
    // 处理透传消息
    if (message.payload.isNotEmpty) {
      try {
        final Map<String, dynamic> payload = json.decode(message.payload);
        // 根据payload处理业务逻辑
        print('透传消息payload: $payload');
      } catch (e) {
        print('解析payload失败: $e');
      }
    }
  }

  void handleNotificationClick(PushMessage message) {
    // 处理通知点击事件
    if (message.payload.isNotEmpty) {
      try {
        final Map<String, dynamic> payload = json.decode(message.payload);
        // 根据payload中的数据进行页面跳转
        if (payload.containsKey('page')) {
          Navigator.of(context).pushNamed(payload['page']);
        }
      } catch (e) {
        print('解析payload失败: $e');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return AppView(
      builder: (locale, builder) => GetMaterialApp(
        debugShowCheckedModeBanner: true,
        enableLog: true,
        builder: builder,
        title:
            "锦信", //多任务列表的情况下显示的名称,// TODO 不同的页面修改这个值，比如切换到通讯录 将这个名字改为 锦信-通讯录，锦信-会议，锦信-网盘 Text(Get.context.find<YourState>().title)
        logWriterCallback: Logger.print,
        translations: TranslationService(),
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          // DefaultCupertinoLocalizations.delegate,
        ],
        fallbackLocale: TranslationService.fallbackLocale,
        locale: locale,
        localeResolutionCallback: (locale, list) {
          Get.locale ??= locale;
          return null;
        },
        supportedLocales: [
          const Locale('zh', 'CN'),
          const Locale('en', 'US'),
        ],
        getPages: AppPages.routes,
        initialBinding: InitBinding(),
        initialRoute: AppRoutes.SPLASH,
      ),
    );
  }
}

class InitBinding extends Bindings {
  @override
  void dependencies() {
    Get.put<DBController>(DBController());
    // Get.put<MineLogic>(MineLogic());

    // Get.put<PermissionController>(PermissionController());
    Get.put<PushController>(PushController());
  }
}
